package pl.kosmowska.ewelina.server.dao;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import pl.kosmowska.ewelina.server.jdo.CategoryData;
import pl.kosmowska.ewelina.server.jdo.CategoryItemData;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;



public class CategoryItemDataDAO extends JdoDAOImpl<CategoryItemData> {
	
	
	private static final Logger log = Logger.getLogger(CategoryItemDataDAO.class
			.getName());
	

	  public CategoryItemData findCategoryItemData(String id) {
			return (CategoryItemData) findById(id);

	  }

	  public  List<CategoryData> findCategoryDataByUser() {
	    Long uid = UserDataDAO.getLoggedInUserId();

	    String qfilter = "userId==" + uid + "";

	    PersistenceManager pm = getPersistenceManager();
	    try {
	      javax.jdo.Query query = pm.newQuery("select from " + CategoryData.class.getName());
	      query.setFilter(qfilter);
	      List<CategoryData> list = (List<CategoryData>) query.execute();

	      List<CategoryData> r = (List<CategoryData>) pm.detachCopyAll(list);

	      return r;
	    } catch (Exception e) {
	      log.log(Level.SEVERE, "Error: Category.findCategory(): qfilter=" + qfilter, e);
	      e.printStackTrace();
	    } finally {
	      pm.close();
	    }
	    return null;
	  }

	  public CategoryItemData persist(CategoryItemData categoryItemData) {
		  return (CategoryItemData) persistEntity(categoryItemData);

	  }
	  
	  public static Boolean deleteCategoryItemData(String id) {
		    
		    if (id == null) {
		      return false;
		    }
		    Long uid = UserDataDAO.getLoggedInUserId();
		    
		    Key key = KeyFactory.stringToKey(id);
		    
		    Boolean success = false;
		    PersistenceManager pm = getPersistenceManager();
		    Transaction tx = pm.currentTransaction();
		    try {
		      
		      CategoryItemData e = pm.getObjectById(CategoryItemData.class, key);
		      if (e.getUserId() != uid) { // check owner
		        log.severe("CategoryItemData.remove() Error: Something weird going on in setting UID. e.getUserId()=" + e.getUserId() + " uid=" + uid);
		        success = false;
		        
		      } else {
		        tx.begin();
		        pm.deletePersistent(e);
		        tx.commit();
		        success = true;
		      }
		      
		    } catch (Exception e) {
		      log.log(Level.SEVERE, "Error:", e);
		      e.printStackTrace();
		    } finally {
		      if (tx.isActive()) {
		        tx.rollback();
		        success = false;
		      }
		      pm.close();
		    }
		    
		    return success;
		  }

}